// 新增重连配置参数类型（可扩展）
const DEFAULT_RECONNECT_OPTIONS = {
  maxRetries: 10,              // 最大重连次数
  initialDelay: 1000,         // 初始重连延迟(ms)
  maxDelay: 30000,            // 最大重连延迟(ms)
  backoffFactor: 2,           // 退避因子（指数增长）
  autoReconnect: false,         // 是否自动重连
};
export async function createWebsocket(url, reconnectOptions = {}, socketHandler = {}) {
  const options = { ...DEFAULT_RECONNECT_OPTIONS, ...reconnectOptions };
  let retryCount = 0;
  let isManualClose = false;
  const connect = () => {
    const socket = new WebSocket(url);

    // 核心事件监听
    socket.onopen = () => {
      retryCount = 0;
      socketHandler.onopen?.(socket);
    };

    socket.onmessage = (data) => {
      socketHandler.onmessage?.(socket, data);
    };

    socket.onclose = (e) => {
      socketHandler.onclose?.(socket);
      if (!isManualClose && options.autoReconnect) {
        scheduleReconnect();
      }
    };

    socket.onerror = (e) => {
      console.error(`WebSocket异常`, e);
      socketHandler.onerror?.(socket);
      if (!isManualClose && options.autoReconnect) {
        scheduleReconnect();
      }
    };
    return socket;
  };

  const scheduleReconnect = () => {
    if (retryCount >= options.maxRetries) {
      console.warn(`已达最大重连次数(${options.maxRetries})`);
      return;
    }
    const delay = Math.min(
      options.initialDelay * Math.pow(options.backoffFactor, retryCount),
      options.maxDelay
    );
    setTimeout(() => {
      retryCount++;
      console.log(`第${retryCount}次重连尝试...`);
      socket = connect(); // 重新创建连接
    }, delay);
  };
  let socket = connect();
  return {
    instance: socket,
    close: () => {
      isManualClose = true;
      closeWebsocket(socket);
    }
  };
}

export function closeWebsocket(instance) {
  if (instance) {
    instance.close();
    instance.onclose = (evt) => {
      console.log('websocket已关闭');
    };
  }
}
